package com.tao.plan.common.utils;


import com.tao.plan.common.exception.EmailBandingException;
import com.tao.plan.domain.pojo.PCommonPlan;
import com.tao.plan.domain.pojo.PCountDownDay;
import com.tao.plan.domain.pojo.PCountPlan;
import com.tao.plan.domain.pojo.PMemoryDay;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 邮箱工具类
 */
@Component
public class EmailUtil {
	@Autowired
	private JavaMailSender mailSender;

	@Value("${spring.mail.username}")
	private String fromEmail;
	/**
	 * 发送 HTML 格式的邮件
	 * @param to 收件人邮箱
	 * @param subject 邮件主题
	 * @param content HTML 格式的邮件内容
	 */
	public void sendHtmlMail(String to, String subject, String content){
		// 创建 MimeMessage 对象
		try{

		MimeMessage message = mailSender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(message, true);
		helper.setFrom(fromEmail);
		helper.setTo(to);
		helper.setSubject(subject);
		// content 需要是 html格式的
		helper.setText(content, true); // 第二个参数为 true，表示内容为 HTML
		// 发送邮件
		mailSender.send(message);
		} catch (Exception e){
			throw new EmailBandingException("发送邮件失败");
		}
	}


	// 读取HTML文件内容并替换验证码
	public String readCodeHtmlTemplate(String filePath, String verificationCode){
		StringBuilder content = new StringBuilder();
		Resource resource = new ClassPathResource(filePath);
		try {
			filePath = resource.getFile().getPath();
		} catch (IOException e) {
			throw new EmailBandingException("邮件内容读取失败1");
		}
		try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
			String line;
			while ((line = reader.readLine()) != null) {
				content.append(line).append("\n");
			}
		}catch (Exception e){
			throw new EmailBandingException("邮件内容读取失败2");

		}
		// 替换占位符
		return content.toString().replace("{{verificationCode}}", verificationCode);
	}

	// 读取html 文件, 并将文件内容替换成计划
	public String readPlanHtmlTemplate(String filePath, List<PCommonPlan> pCommonPlans, List<PCountPlan> countPlans){
		StringBuilder content = new StringBuilder();
		Resource resource = new ClassPathResource(filePath);
		try {
			filePath = resource.getFile().getPath();
		} catch (IOException e) {
			throw new EmailBandingException("邮件内容读取失败1");
		}
		try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
			String line;
			while ((line = reader.readLine()) != null) {
				content.append(line).append("\n");
			}
		}catch (Exception e){
			throw new EmailBandingException("邮件内容读取失败2");
		}

		StringBuilder studySb = new StringBuilder();
		StringBuilder workSb = new StringBuilder();
		StringBuilder lifeSb = new StringBuilder();
		StringBuilder countSb = new StringBuilder();
		pCommonPlans.forEach(item->{
			String li = "<li>"+ item.getTitle() +", 优先级数<span class=\"task-count\">"+ item.getPriority() +"</span></li>\n";
			if (item.getType() == 0){
				// 学习
				studySb.append(li);
			} else if (item.getType() == 1) {
				// 工作
				workSb.append(li);
			}else {
				// 生活
				lifeSb.append(li);
			}
		});
		countPlans.forEach(item->{
			String li = "<li>"+item.getTitle()+"<span class=\"task-count\">已完成"+item.getCount()+"</span>次</li>";
			countSb.append(li);
		});
		// TODO 如果没有计划怎么办, 加一个默认的暂无计划
		return content.toString()
				.replace("${study_plan}", studySb)
				.replace("${work_plan}", workSb)
				.replace("${life_plan}", lifeSb)
				.replace("${count_plan}", countSb);
	}
	// 读取html 文件, 并将文件内容替换成纪念日
	public String readMemoryDayHtmlTemplate(String filePath, List<PMemoryDay> memoryDays, List<PCountDownDay> countDownDays){
		StringBuilder content = new StringBuilder();
		Resource resource = new ClassPathResource(filePath);
		try {
			filePath = resource.getFile().getPath();
		} catch (IOException e) {
			throw new EmailBandingException("邮件内容读取失败1");
		}
		try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
			String line;
			while ((line = reader.readLine()) != null) {
				content.append(line).append("\n");
			}
		}catch (Exception e){
			throw new EmailBandingException("邮件内容读取失败2");
		}
		StringBuilder memorySb = new StringBuilder();
		StringBuilder countDownSb = new StringBuilder();
		for (PMemoryDay memoryDay : memoryDays) {
			String time = memoryDay.getType() == 0?"公历":"农历" + memoryDay.getTargetTime().getMonth() + "-" + memoryDay.getTargetTime().getDayOfMonth();
			String text = "<li>"+memoryDay.getTitle()+"：<span class=\"anniversary\">"+time+"</span></li>";
			memorySb.append(text);
		}
		for (PCountDownDay countDownDay : countDownDays) {
			LocalDateTime targetTime = countDownDay.getTargetTime();
			Integer nextDays = DateUtil.getNextDays(targetTime, false);
			String text = "<li>"+countDownDay.getTitle()+"：<span class=\"countdown\">"+nextDays+" 天</span></li>";
			countDownSb.append(text);
		}
		return content.toString().replace("${memory_day}",memorySb).replace("${coutdown_day}",countDownSb);
	}
}
